package com.lkd.http.controller;
import com.lkd.common.VMSystem;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.vo.PayVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPaySDKUtil wxPaySDKUtil;

    /**
     * 下单
     * @param payVO
     * @return
     */
    @PostMapping("/weixinPay")
    public String weixinPay(@RequestBody PayVO payVO){
        OrderEntity order = orderService.createOrder(payVO);
        //封装支付对象，
        WxPayDTO wxPayDTO=new WxPayDTO();
        wxPayDTO.setBody(order.getSkuName());
        wxPayDTO.setOpenid(order.getOpenId());
        wxPayDTO.setTotalFee(order.getAmount());
        wxPayDTO.setOutTradeNo(order.getOrderNo());
        //调用微信支付,返回结果
        return wxPaySDKUtil.requestPay(wxPayDTO);
    }

    /**
     * 支付完成后的回调接口，修改订单和支付状态为已完成
     * @param request
     * @param response
     */
    @RequestMapping("/payNotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("调用了回调方法");
        try {
            //输入流转化为xml文件
//            String notifyResult = ConvertUtils.convertToString(request.getInputStream());
//            String orderSn = wxPaySDKUtil.validPay(notifyResult);
            //测试环境简陋，无法使用微信回调，模拟假数据调用接口，改变订单和支付状态；
            String orderSn="01000001830103316286000";
            if(orderSn!=null){
                log.info("修改订单状态和支付状态");
                OrderEntity order = orderService.getByOrderNo(orderSn);
                order.setStatus(VMSystem.ORDER_STATUS_PAYED);
                order.setPayStatus(VMSystem.PAY_STATUS_PAYED);

                orderService.updateById(order);
                response.setContentType("text/xml");
                response.getWriter().write(WXConfig.RESULT);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("支付回调处理失败");
        }

    }



}
